package com.wlyy.his.infrastructure.interceptor;


import com.alibaba.fastjson.JSON;
import com.wlyy.his.common.api.ResultCode;
import com.wlyy.his.common.exception.ApiException;
import com.wlyy.his.common.util.RedisUtil;
import com.wlyy.his.common.util.theadLocal.UserUtils;
import com.wlyy.his.infrastructure.common.AuthCommon;
import com.wlyy.his.infrastructure.common.RequestUserInfo;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录验证
 * @author zhouyanhui
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;
    /**
     * 登录验证 进入controller层之前拦截请求
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o) throws ApiException {
        String token = httpServletRequest.getHeader("token");
        if (null!=token){
            String method = httpServletRequest.getMethod();
            //处理预请求
            if (HttpMethod.OPTIONS.toString().equals(method)) {
                return true;
            } else {
                boolean exist = redisUtil.hasKey(AuthCommon.CACHE_USER_REDIS_KEY + token);
                if (exist){
                    Object obj = redisUtil.get(AuthCommon.CACHE_USER_REDIS_KEY + token);
                    if (null==obj){
                        throw (new ApiException(ResultCode.UNAUTHORIZED));
                    }
                    //转换给当前请求使用
                    UserUtils.setLoginUser(String.valueOf(obj));
//                    requestUserInfo = JSON.parseObject(JSON.toJSONString(obj), RequestUserInfo.class);
                    redisUtil.expire(AuthCommon.CACHE_USER_REDIS_KEY + token, AuthCommon.TOKEN_CACHE_TIME);
                    return true;
                }
            }
        }
        throw (new ApiException(ResultCode.UNAUTHORIZED));
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)  {
    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)  {
    }
}


